// 试题库
<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!--模型数据-->
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="试题名称" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入试题名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="因子类型" prop="usingStatus">
            <el-select
              v-model="queryParams.usingStatus"
              placeholder="请选择因子类型"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.item_factor"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="queryParams.createDate"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="date"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
              >删除</el-button
            >
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="试题ID" align="center" key="id" prop="id" />
          <el-table-column
            label="试题名称"
            align="center"
            key="title"
            prop="title"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="试题类型"
            align="center"
            key="factorText"
            prop="factorText"
            width="160"
          />

          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-share"
                @click="handleUpdate(scope.row, '详情')"
                v-hasPermi="['system:user:edit']"
                >详情</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
    >
      <el-form ref="form" label-width="80px">
        <!-- 添加试题 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="tryAdd"
              :disabled="displays"
              v-if="title !== '编辑量表模版'"
              >添加</el-button
            >
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table
              v-loading="loading"
              :data="elements"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column
                label="序号"
                align="center"
                key="orderNum"
                prop="orderNum"
                width="80"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.orderNum" :disabled="displays" />
                </template>
              </el-table-column>
              <el-table-column
                label="试题"
                align="center"
                prop="title"
                width="480"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.title"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入内容"
                    :disabled="displays"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="类型" align="center" prop="factor">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.factor"
                    placeholder="请选择因子类型"
                    clearable
                    style="width: 240px"
                    :disabled="displays"
                  >
                    <el-option
                      v-for="dict in dict.type.item_factor"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="uploadTemplatee(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="dislodge(scope.row)"
                    :disabled="displays"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="900px"
      append-to-body
    >
      <div class="subject">{{ editAnswer.title }}</div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="answerAdd"
            :disabled="displays"
            >添加</el-button
          >
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-table v-loading="loading" :data="answerLiat">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="答案内容" align="center" prop="optionText">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.optionText"
                  placeholder="请输入答案内容"
                  :disabled="displays"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="答案分值" align="center" prop="score">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.score"
                  placeholder="请输入答案分值"
                  :disabled="displays"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="dislodge(scope.row, '答案')"
                  :disabled="displays"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  questionSave, //添加试题库
  questionPut, //修改试题
  questionDel, //删除试题
  questionPage, //试题列表
  questionDtail, //试题详情
} from "@/api/itemBank/index";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  efficacy, //试题必填效验
} from "@/utils/verification";

export default {
  dicts: ["sys_normal_disable", "item_factor", "yes_no_switch"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 类型选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      moreNoe: [
        { label: "单选题", value: "1" },
        { label: "多选题", value: "2" },
      ],
      //   答案表
      answerLiat: [],
      editAnswer: {}, //回显试题内容
      displays: false, //禁止输入
      // 表单参数
      elements: [
        {
          title: null, // 题目
          orderNum: "1", //编号
          factor: null,
          selectionItemEntityList: [
            {
              optionText: null,

              score: "0",
            },
          ],
        },
      ], //选择题
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },

      // 表单校验
      rules: {},
    };
  },
  watch: {},
  created() {
    this.getList();
  },
  methods: {
    // 上传封面
    getaDOCtament(urls) {
      this.form.coverPhoto = urls;
    },
    // 删除封面
    celetePicture() {
      this.form.coverPhoto = null;
    },
    /** 查询量表列表 */
    getList() {
      this.loading = true;
      questionPage(this.queryParams).then((response) => {
        console.log("response.rows", response);
        this.userList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    // 添加试题
    tryAdd() {
      this.elements.push({
        title: null, // 题目
        orderNum: this.elements.length + 1, //编号
        factor: null,
        selectionItemEntityList: [
          {
            optionText: null,
            score: "0",
          },
        ],
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      (this.elements = [
        {
          title: null, // 题目
          orderNum: "1", //编号
          factor: null,
          selectionItemEntityList: [
            {
              optionText: null,
              score: "0",
            },
          ],
        },
      ]), //选择题
        this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log("查询", this.dateRange);

      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题";
      this.displays = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.elements = [];
      this.reset();
      if (type == "详情") {
        this.title = "量表模版详情";
        this.displays = true;
      } else {
        this.title = "编辑量表模版";
        this.displays = false;
      }
      this.elements[0] = row;
      questionDtail(row.id).then((response) => {
        this.elements[0].selectionItemEntityList = response.data;
        this.open = true;
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      if (efficacy(this.elements) !== "") {
        this.$modal.msgError(efficacy(this.elements));
      } else {
        if (this.elements[0].id != undefined) {
          this.elements[0].selectionItemEntityList.map(item=>item.id=null)

          questionPut(this.elements[0]).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          questionSave(this.elements).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + userIds + '"的数据项？')
        .then(function () {
          return questionDel(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 启用
    enable(row, status) {
      let data = {
        id: row.id,
        usingStatus: status,
      };
      let typetext = status == 0 ? "启用" : "禁用";

      this.$modal
        .confirm("确认" + typetext + '量表编号为"' + row.id + '"的数据项？')
        .then(function () {
          return formcfgStatus(data);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(typetext + "成功");
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    //上传答案
    uploadTemplatee(row) {
      console.log("55", row);

      this.answerLiat = row.selectionItemEntityList;
      this.editAnswer = row;
      this.upload.title = "答案上传";
      this.upload.open = true;
    },
    // 删除
    dislodge(row, text) {
      if (text == "答案") {
        this.answerLiat.splice(
          this.answerLiat.findIndex(
            (item) => item.optionText === row.optionText
          ),
          1
        );
      } else {
        this.elements.splice(
          this.elements.findIndex((item) => item.orderNum === row.orderNum),
          1
        );
      }
    },
    // 添加答案
    answerAdd() {
      this.answerLiat.push({
        optionText: "",
        score: "0",
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "批量导入";
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传答案
    submitFileForm() {
      this.elements.forEach((item) => {
        if (
          item.title == this.editAnswer.title &&
          item.orderNum == this.editAnswer.orderNum
        ) {
          item.selectionItemEntityList = this.answerLiat;
          this.upload.open = false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.subject {
  width: 100%;
  margin-top: -30px;
  margin-bottom: 10px;
  font-size: 18px;
  padding-left: 5px;
}
</style>

